﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Diagnostics;
using VirtuOS.Components;
using VirtuOS.Components.Commands;
using VirtuOS.Base;
using System.Reflection;

namespace VirtuOS
{
    class InputHandler
    {
        public static String Masked(String Question)
        {
            Console.CursorVisible = false;
            Console.Write(Question);
            StringBuilder sb = new StringBuilder();
            while (true)
            {
                ConsoleKeyInfo cki = Console.ReadKey(true);
                if (cki.Key == ConsoleKey.Enter)
                {
                    Console.WriteLine();
                    break;
                }
                if (cki.Key == ConsoleKey.Backspace)
                {
                    if (sb.Length > 0)
                    {
                        Console.Write("\b");
                        sb.Length--;
                    }
                    continue;
                }
                Console.Write("");
                sb.Append(cki.KeyChar);
            }
            Console.CursorVisible = true;
            return sb.ToString();
        }

        public static void RequiresRoot(string s) { Console.WriteLine("You do not have permission to use `{0}`.", s); }

        public static void CommandHandler(string input)
        {
            string[] s = input.Split(' ');
            string[] args = new string[s.Length - 1];
            for (int i = 0; i < args.Length; i++)
            {
                args[i] = s[i + 1];
            }
            if (s.Length > 0)
            {
                if (list.clist.Contains(s[0]))
                {
                    Assembly cmdinvoke = Assembly.GetExecutingAssembly();
                    Type[] ctypes = cmdinvoke.GetTypes();

                    foreach (Type t in ctypes)
                    {
                        if ((t.Namespace.Contains("Components.Commands")) && (t.Name.Equals(s[0])))
                        {
                            object instance = Activator.CreateInstance(t);
                            instance.GetType().InvokeMember("Command", BindingFlags.Public | 
                                BindingFlags.Static | BindingFlags.InvokeMethod, null, null, 
                                new object[] { args });
                        }
                    }
                }
            }
        }
    }
}
